package study.datastructure.leetcode.javase.primary.mutithreads;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-09-08 14:48
 */

import com.sun.corba.se.spi.ior.ObjectKey;
import jdk.internal.dynalink.beans.StaticClass;

/**
 2024/9/8,
 */

/*【编程题】请用等待/唤醒机制编写一个程序，要求：
        第一个线程：遍历
        [1,1000] 中所有的数字，在遍历过程中，如果发现这个数字能同时被 2,3,5整除，立即 wait() 等待，让第二个线程进入。
        第二个线程：运行时，将一个计数器+1 然后唤醒等待的线程。 主线程：睡眠2 秒，
        让两个线程全部执行完毕，打印计数器的结果。*/
public class ClientWork {
    private static final Object lock = new Object();
    static int number = 0;
    static boolean isEnd = false;
    static boolean isNotify = false;

    public static void main(String[] args) throws InterruptedException {
            Thread thread1 = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    synchronized (lock) {
                        if (i % 2 == 0 && i % 3 == 0 && i % 5 == 0) {
                            System.out.println("number " + i + "被 2 3 5 整除"); // ?
                            lock.notify();
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
                synchronized (lock) {
                    lock.notifyAll(); //最后走之前唤醒入睡线程
                }
            });


            Thread thread2 = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    if (i % 2 == 0 && i % 3 == 0 && i % 5 == 0) {
                        synchronized (lock) {
                            number++;
                            lock.notifyAll();
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            });
            long start = System.currentTimeMillis();
            thread1.start();
            thread2.start();
            Thread.sleep(2000);

            System.out.println("事件间隔耗时:" + (System.currentTimeMillis() - start));
            System.out.println("number是" + number);
            System.out.println(".......");

        }

}